<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\service\RuleService;
use think\facade\View;
use think\facade\Request;
use app\common\Error;
use think\facade\Cache;

class Base extends BaseController
{
    protected $middleware = ['check_admin_login', 'check_admin_auth'];
    // protected $middleware = ['check_admin_login'];

    public $menu;
    private $service;

    public function __construct()
    {
        $this->service = new RuleService();

        $header = Request::header();
        if (!empty($header['token'])) {
            $token = $header['token'];
        } else if (!empty(Request::param()['token'])) {
            $token = Request::param()['token'];
        } else {
            $token = '';
        }

        if (empty($token)) {
            return redirect(url('admin/login/index'));
        }

        self::getMenuData($token);
    }

    // 获取菜单数据
    public function getMenuData($token)
    {
        $redis = Cache::store('redis')->handler();
        $redis->select(3);

        $userInfo = $redis->get($token);
        $userInfo = json_decode($userInfo, true);

        if (empty($userInfo) || empty($userInfo['user_id'])) {
            return redirect(url('admin/login/index'));
        }
        $data = $this->service->getMenuData($userInfo);

        // $this->menu = $data;
        View::assign('menu_data', $data);
    }

    /**
     * 获取用户信息
     * @return mixed
     */
    public function getUserInfo()
    {
        $header = Request::header();
        if (!empty($header['token'])) {
            $token = $header['token'];
        } else if (!empty(Request::param()['token'])) {
            $token = Request::param()['token'];
        } else {
            $token = '';
        }

        if (empty($token)) {
            return redirect(url('admin/login/index'));
            // return ['code' => Error::FAIL_CODE, 'message' => Error::TOKEN_NOT_EXIXTS];
        }

        $redis = Cache::store('redis')->handler();
        $redis->select(3);
        $data = $redis->get($token);

        return json_decode($data, true);
    }
}